from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from allmodels.models import SysConfig
from django.shortcuts import get_object_or_404
from django.utils.timezone import now
from rest_framework.permissions import IsAuthenticated


from rest_framework.views import APIView
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.utils import timezone
from login.views import verify_token
import json
from django.core.cache import cache
from rest_framework.views import APIView
from django.http import JsonResponse
from django.core.paginator import Paginator
from django.db.models import Q


class SysConfigUpdateView(APIView):
    def put(self, request, id):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取系统配置对象
        sys_config = get_object_or_404(SysConfig, pk=id, is_deleted=False)

        # 获取请求体中的参数
        config_name = request.data.get('configName')
        config_key = request.data.get('configKey')
        config_value = request.data.get('configValue')
        remark = request.data.get('remark', '')

        # 验证必填项
        if not config_name or not config_key or not config_value:
            return JsonResponse({
                'code': '10006',
                'msg': '缺少必需的参数'
            }, status=400)

        # 更新配置
        sys_config.config_name = config_name
        sys_config.config_key = config_key
        sys_config.config_value = config_value
        sys_config.remark = remark
        sys_config.update_time = timezone.now()
        sys_config.update_by = request.user.id  # 假设请求中有用户ID
        sys_config.save()

        # 返回更新成功的响应
        return JsonResponse({
            "code": "00000",
            "data": {
                "id": sys_config.id,
                "configName": sys_config.config_name,
                "configKey": sys_config.config_key,
                "configValue": sys_config.config_value,
                "remark": sys_config.remark
            },
            "msg": "更新成功"
        }, status=200)

# class SysConfigDeleteView(APIView):
    def delete(self, request, id):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取要删除的系统配置项
        sys_config = get_object_or_404(SysConfig, pk=id, is_deleted=False)

        # 标记为逻辑删除
        sys_config.is_deleted = True
        sys_config.save()

        # 返回删除成功的响应
        return JsonResponse({
            "code": "00000",
            "data": {},
            "msg": "删除成功"
        }, status=200)

class SysConfigCreateView(APIView):
    def post(self, request):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取请求体数据
        try:
            data = json.loads(request.body)
            config_name = data.get('configName')
            config_key = data.get('configKey')
            config_value = data.get('configValue')
            remark = data.get('remark', '')

            # 检查必填项是否存在
            if not config_name or not config_key or not config_value:
                return JsonResponse({
                    'code': '10006',
                    'msg': '缺少必填项：configName、configKey 或 configValue'
                }, status=400)

            # 创建系统配置
            sys_config = SysConfig(
                config_name=config_name,
                config_key=config_key,
                config_value=config_value,
                remark=remark,
                create_by=payload.get('user_id')
            )
            sys_config.save()

            # 返回成功响应
            return JsonResponse({
                "code": "00000",
                "data": {
                    "id": sys_config.id,
                    "configName": sys_config.config_name,
                    "configKey": sys_config.config_key,
                    "configValue": sys_config.config_value,
                    "remark": sys_config.remark
                },
                "msg": "新增成功"
            }, status=200)

        except json.JSONDecodeError:
            return JsonResponse({
                'code': '10007',
                'msg': '请求体数据格式有误'
            }, status=400)

# class SysConfigRefreshCacheView(APIView):
    def patch(self, request):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 刷新系统配置缓存
        try:
            # 获取所有系统配置数据
            config_list = SysConfig.objects.all()
            config_dict = {}

            # 将配置存入字典，并刷新缓存
            for config in config_list:
                config_dict[config.config_key] = config.config_value

            # 更新缓存
            cache.set('sys_config', config_dict, timeout=None)  # None 表示永久存储

            return JsonResponse({
                "code": "00000",
                "data": config_dict,
                "msg": "系统配置缓存刷新成功"
            }, status=200)

        except Exception as e:
            return JsonResponse({
                "code": "10006",
                "msg": f"缓存刷新失败: {str(e)}"
            }, status=500)

class SysConfigFormView(APIView):
    def get(self, request, id):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 查询系统配置表单数据
            config = SysConfig.objects.get(id=id)

            # 构建返回的数据结构
            config_data = {
                "id": config.id,
                "configName": config.config_name,
                "configKey": config.config_key,
                "configValue": config.config_value,
                "remark": config.remark
            }

            return JsonResponse({
                "code": "00000",
                "data": config_data,
                "msg": "获取系统配置表单数据成功"
            }, status=200)

        except SysConfig.DoesNotExist:
            return JsonResponse({
                "code": "10001",
                "msg": "系统配置未找到"
            }, status=404)

        except Exception as e:
            return JsonResponse({
                "code": "10006",
                "msg": f"系统配置表单数据获取失败: {str(e)}"
            }, status=500)

class SysConfigPageView(APIView):
    def get(self, request):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取查询参数
        keywords = request.GET.get('keywords', '')
        page_num = int(request.GET.get('pageNum', 1))
        page_size = int(request.GET.get('pageSize', 10))

        # 构建查询条件
        filters = Q()
        if keywords:
            filters &= Q(config_name__icontains=keywords) | Q(config_value__icontains=keywords)

        # 查询系统配置
        config_query = SysConfig.objects.filter(filters).order_by('id')
        paginator = Paginator(config_query, page_size)
        configs_page = paginator.get_page(page_num)

        # 构建返回的数据结构
        config_list = []
        for config in configs_page:
            config_list.append({
                "id": config.id,
                "configName": config.config_name,
                "configKey": config.config_key,
                "configValue": config.config_value,
                "remark": config.remark,
            })

        # 返回分页数据
        return JsonResponse({
            "code": "00000",
            "data": {
                "list": config_list,
                "total": paginator.count
            },
            "msg": "一切ok"
        }, status=200)